<template>
    <view>
        <!-- pages/mine_favorite/mine_favorite.wxml -->

        <view class="messageList borderShowdow">
            <block v-for="(cellItem, cellIdx) in datalist" :key="cellItem.cellIdx">
                <view class="classCell" :id="cellIdx" @tap="cellClick">
                    <image class="class-cell-avatar" :src="userAvatar + cellItem.uid"></image>
                    <view class="class-cell-contentView">
                        <view class="username">
                            {{ cellItem.nickname ? cellItem.nickname : cellItem.author }}
                        </view>
                        <view class="message">{{ cellItem.title }}</view>

                        <view class="attachementView" v-if="cellItem.attachments.length > 0">
                            <block v-for="(attItem, imageidx) in cellItem.imageA" :key="attItem.aid">
                                <image
                                    class="attachement"
                                    :src="attItem.attachurl"
                                    :id="imageidx"
                                    :data-cellindex="cellIdx"
                                    @tap.stop.prevent="lookImage"
                                    v-if="(cellItem.videoA && imageidx < 8) || (!cellItem.videoA && imageidx < 9)"
                                ></image>
                            </block>
                            <block v-for="(video, aidx) in cellItem.videoA" :key="video.aid">
                                <image @tap.stop.prevent="clickVideo" :id="video.attachurl" class="attachement" :src="minImgDoc + 'videoPlace.png'"></image>
                            </block>

                            <block v-if="cellItem.imageA.length == 0 && cellItem.videoA.length == 0 && cellItem.audioA">
                                <block v-if="aidx == 0" v-for="(audio, aidx) in cellItem.audioA" :key="audio.aid">
                                    <!-- parse <template is="audio_player" :data="...audio.toolUse,minImgDoc"/> -->
                                    <block name="audio_player">
                                        <view class="audio-playView">
                                            <image
                                                :src="is_play && currentAudio == attachment ? minImgDoc + 'audio_play.png' : minImgDoc + 'audio_paused.png'"
                                                class="audio-icon audio-play"
                                                :data-listindex="listIndex"
                                                @tap.stop.prevent="audio_play"
                                                :id="attachment"
                                            ></image>
                                            <view class="control-process">
                                                <text class="current-process">
                                                    <block v-if="current_process.length > 0 && currentAudio == attachment">
                                                        {{ current_process }}
                                                    </block>
                                                    <block v-else>00:00</block>
                                                </text>

                                                <text class="total-process">
                                                    <block>
                                                        {{ total_process }}
                                                    </block>
                                                </text>
                                                <slider
                                                    class="slider"
                                                    @change="hanle_slider_change"
                                                    @touchstart="handle_slider_move_start"
                                                    @touchend="handle_slider_move_end"
                                                    min="0"
                                                    block-size="12"
                                                    block-color="#6199fd"
                                                    :max="slider_max"
                                                    activeColor="#5abf39"
                                                    backgroundColor="rgb(153,153,153,0.4)"
                                                    :value="currentAudio == attachment ? slider_value : 0"
                                                />
                                            </view>
                                        </view>
                                    </block>
                                </block>
                            </block>
                        </view>
                        <rich-text class="class-cell-time" :nodes="cellItem.dateline"></rich-text>
                        <view class="toolRight">
                            <view class="shareHidden borderShowdow" v-if="cellItem.shareshow == 1">
                                <button open-type="share" :plain="true" @tap.stop.prevent="listShare" :id="cellIdx">
                                    <image class="shareIcon" :src="minImgDoc + 'workshare.png'"></image>
                                </button>
                                <button :plain="true" @tap.stop.prevent="disVoice" :id="cellIdx">
                                    <image class="shareIcon" :src="minImgDoc + 'workvoice.png'"></image>
                                </button>
                            </view>
                            <image src="" class="discIcon" :src="minImgDoc + 'cpostmessage.png'" @tap.stop.prevent="discClick" :data-tid="cellItem.tid" :id="cellIdx"></image>
                        </view>
                    </view>
                </view>
            </block>
            <view class="emptyView" v-if="datalist.length <= 0">
                <view style="width: 100%; height: 10rpx"></view>
                <image :src="minImgDoc + 'minefavEmpty.png'"></image>
                <view class="emptyMsg">真正的懒神就是一篇内容都没有</view>
            </view>
        </view>
        <view class="noMoreView" v-if="noMore">别再用力了，你已经滑到底啦</view>
        <video id="myVideo" :autoplay="true" @play="playVideo" @fullscreenchange="fullScreenChange" :src="currentVideo"></video>
    </view>
</template>

<script>
// pages/mine_favorite/mine_favorite.js
const myFavoriteUrl = require('../../config').myFavoriteUrl;

const util = require('../../utils/util.js');

const minImgDoc = require('../../config').minImgDoc;

const userAvatar = require('../../config').userAvatar;

const app = getApp();

export default {
    data() {
        return {
            userAvatar,
            minImgDoc: minImgDoc,
            pagenum: 1,
            noMore: false,
            datalist: '',
            is_moving_slider: false,
            currentAudio: '',
            currentVideo: '',

            cellItem: {
                cellIdx: '',
                uid: '',
                nickname: false,
                author: '',
                title: '',
                attachments: [],
                imageA: [],
                videoA: '',
                audioA: '',
                dateline: '',
                shareshow: 0,
                tid: ''
            },

            cellIdx: 0,

            attItem: {
                aid: '',
                attachurl: ''
            },

            imageidx: 0,

            video: {
                aid: '',
                attachurl: ''
            },

            aidx: 0,

            audio: {
                aid: ''
            },

            is_play: '',
            attachment: '',
            listIndex: [],
            current_process: [],
            total_process: '',
            slider_max: '',
            slider_value: ''
        };
    },
    onReady() {},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        this.requestData();
        this.videoContext = uni.createVideoContext('myVideo');
        this.setupAudioPlayer();
    },
    onPullDownRefresh: function () {
        this.requestMore(false);
    },
    onReachBottom: function () {
        this.requestMore(true);
    },
    methods: {
        requestData() {
            app.globalData.apimanager
                .getRequest(myFavoriteUrl, {
                    page: this.pagenum
                })
                .then((res) => {
                    uni.stopPullDownRefresh();
                    let dataArr = res.Variables.list ? res.Variables.list : [];

                    if (dataArr.length > 0) {
                        this.noMore= false;
                    } else {
                        this.noMore= true;
                    }

                    var usernicknames = res.Variables.usernicknames;

                    for (let i = 0; i < dataArr.length; i++) {
                        let postItem = dataArr[i];

                        if (postItem.author) {
                            postItem.nickname = postItem.author;
                        } else {
                            if (postItem.author === null) {
                                postItem.nickname = '已删除';
                            } else {
                                postItem.nickname = '匿名';
                            }
                        }

                        postItem.dateline = util.formatTimeTwo(postItem.dateline, 'Y-M-D');

                        if (usernicknames) {
                            if (usernicknames[postItem.authorid]) {
                                postItem.nickname = usernicknames[postItem.authorid];
                            }
                        } // 附件处理

                        let attachments = postItem.attachments;
                        let imageA = [];
                        let audioA = [];
                        let videoA = [];

                        for (let k in attachments) {
                            let attItem = attachments[k];

                            if (attItem.isimage == -1) {
                                imageA.push(attItem);
                            } else {
                                if (attItem.attachment.indexOf('mp3') != -1) {
                                    let total_process = '00:00';

                                    if (attItem.description) {
                                        total_process = util.formatTime(parseInt(attItem.description));
                                    }

                                    attItem['toolUse'] = {
                                        attachment: attItem.attachurl,
                                        listIndex: i,
                                        total_process: total_process
                                    };
                                    audioA.push(attItem);
                                } else {
                                    if (attItem.attachment.indexOf('mp4') != -1) {
                                        videoA.push(attItem);
                                    }
                                }
                            }
                        }

                        postItem['imageA'] = imageA;
                        postItem['audioA'] = audioA;
                        postItem['videoA'] = videoA;
                    }

                    if (this.pagenum > 1) {
                        dataArr = this.datalist.concat(dataArr);
                    }

                    this.datalist= dataArr;
                })
                .catch((res) => {
                    uni.stopPullDownRefresh();
                });
        },

        requestMore(isMore) {
            if (isMore) {
                this.pagenum += 1;
            } else {
                this.pagenum = 1;
            }

            this.requestData();
        },

        cellClick(e) {
            var tid = this.datalist[e.currentTarget.id].id;
            uni.navigateTo({
                url: '../thread_detail/thread_detail?tid=' + tid
            });
        },

        lookImage(e) {
            let cellItem = this.datalist[e.currentTarget.dataset.cellindex];
            let imageA = cellItem.imageA;
            var imageSrcArray = [];

            for (let i = 0; i < imageA.length; i++) {
                let item = imageA[i];
                imageSrcArray.push(item.attachurl);
            }

            uni.previewImage({
                current: imageSrcArray[e.currentTarget.id],
                urls: imageSrcArray
            });
        },

        /* *********************** 播放语音相关start *********** */
        setupAudioPlayer() {
            this.innerAudioContext = uni.createInnerAudioContext();
            this.innerAudioContext.obeyMuteSwitch = false;
            this.innerAudioContext.onEnded((res) => {
                this.stopVoice();
            });
            this.innerAudioContext.onTimeUpdate(() => {
                if (!this.is_moving_slider) {
                    // 播放中
                    this.currentAudio = this.datalist[this.currentAudio.toolUse.listIndex].audioA[0];
                    console.log('cur', this.currentAudio);
                    let param = {};
                    let toolUsestr = 'datalist[' + this.currentAudio.toolUse.listIndex + '].audioA[0].toolUse';
                    let toolUse = this.currentAudio.toolUse;
                    toolUse['current_process'] = util.formatTime(this.innerAudioContext.currentTime);
                    toolUse['slider_value'] = Math.floor(this.innerAudioContext.currentTime);
                    toolUse['total_process'] = util.formatTime(this.innerAudioContext.duration);
                    toolUse['slider_max'] = Math.floor(this.innerAudioContext.duration);
                    param[toolUsestr] = toolUse;
                    this.setData(param);
                }
            });
        },

        // 拖动进度条，到指定位置
        hanle_slider_change(e) {
            const position = e.detail.value;
            this.seekCurrentAudio(position);
        },

        // 拖动进度条控件
        seekCurrentAudio(position) {
            this.innerAudioContext.seek(position);
        },

        // 进度条滑动
        handle_slider_move_start() {
            this.is_moving_slider= true;
        },

        handle_slider_move_end() {
            this.is_moving_slider= false;
        },

        // 点击播放暂停
        audio_play(e) {
            let listIndex = e.currentTarget.dataset.listindex;
            let postItem = this.datalist[listIndex];
            console.log('postItem', postItem);
            var param = {};
            let audioset = 'datalist[' + listIndex + '].audioA[0].toolUse.currentAudio';
            param[audioset] = postItem.audioA[0].attachurl;
            this.setData(param);
            let currentAudio = postItem.audioA[0];
            console.log('currentaudio', currentAudio);
            this.currentAudio= currentAudio;
            let isplay = this.currentAudio.toolUse.is_play;
            let playstr = 'datalist[' + listIndex + '].audioA[0].toolUse.is_play';
            param[playstr] = !isplay;
            this.setData(param);

            if (isplay) {
                this.innerAudioContext.pause();
                isplay = false;
            } else {
                if (!isplay && !this.currentAudio.toolUse.is_ended) {
                    this.playVoice();
                } else {
                    this.innerAudioContext.play();
                }
            }

            console.log('currentAudio', currentAudio);
        },

        playVoice() {
            var src = this.currentAudio.attachurl;
            this.innerAudioContext.src = src;
            this.innerAudioContext.play();
        },

        stopVoice() {
            var param = {};
            let listIndex = this.currentAudio.toolUse.listIndex;
            let toolUsestr = 'datalist[' + listIndex + '].audioA[0].toolUse';
            let toolUse = this.currentAudio.toolUse;
            toolUse['is_play'] = false;
            toolUse['slider_value'] = 0;
            toolUse['current_process'] = util.formatTime(0);
            param[toolUsestr] = toolUse;
            this.setData(param);
            this.innerAudioContext.stop();
            let postItem = this.datalist[listIndex];
            this.currentAudio = postItem.audioA[0];
        },

        /* *********************** 语音end *********** */
        // 视频播放
        clickVideo(e) {
            this.currentVideo= e.currentTarget.id;
            this.videoContext.play();
            this.videoContext.requestFullScreen({
                direction: 0
            });
        },

        playVideo() {},

        fullScreenChange(e) {
            console.log(e.detail);

            if (!e.detail.fullScreen) {
                this.videoContext.stop();
            }
        },

        listShare() {
            console.log('占位：函数 listShare 未声明');
        },

        disVoice() {
            console.log('占位：函数 disVoice 未声明');
        },

        discClick() {
            console.log('占位：函数 discClick 未声明');
        }
    }
};
</script>
<style>
@import './mine_favorite.css';
</style>
